package vip.idiy.anwei_android_iot.utils.dbHandle;

import android.content.ContentValues;
import android.database.Cursor;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

import vip.idiy.anwei_android_iot.domin.DeviceData;

import vip.idiy.anwei_android_iot.domin.DeviceScene;
import vip.idiy.anwei_android_iot.utils.DatabaseUtil;

/**
 * ClassName DeviceDataHandle
 * describe:
 * Created: 勇
 * Email:118085890@qq.com
 * Version: 1.0
 * Create in 21:37 2023/4/21
 */
public class DeviceDataHandle {

    private DatabaseUtil databaseUtil;

    private final String DATA_TABLE = "device_data";
    // 每页返回记录数
    private final int LIMIT = 10;


    private final String COLUMNS_ID = "id";
    private final String COLUMNS_DEVICE_ID = "device_id";
    private final String COLUMNS_WIFI_NAME = "wifi_name";
    private final String COLUMNS_WIFI_PSW = "wifi_psw";
    private final String COLUMNS_AUTO_WIFI = "auto_wifi";
    private final String COLUMNS_MQTT_SERVER = "mqtt_server";
    private final String COLUMNS_MQTT_PORT = "mqtt_port";
    private final String COLUMNS_MQTT_NAME = "mqtt_name";
    private final String COLUMNS_MQTT_PSW = "mqtt_psw";
    private final String COLUMNS_MQTT_SUB = "mqtt_sub";
    private final String COLUMNS_MQTT_PUB = "mqtt_pub";

    private final String SELECT_DEVICE_ID = "device_id = ? ";
    private final String SELECT_BY_ID = "id = ? ";

    public DeviceDataHandle(DatabaseUtil databaseUtil) {
        this.databaseUtil = databaseUtil;
    }

    /**
     * 添加数据
     *
     * @param deviceData
     * @return
     */
    public boolean insert(DeviceData deviceData) {
        ContentValues values = new ContentValues();
        values.put(COLUMNS_DEVICE_ID, deviceData.getDeviceId());
        values.put(COLUMNS_WIFI_NAME, deviceData.getWifiName());
        values.put(COLUMNS_WIFI_PSW, deviceData.getWifiPsw());
        values.put(COLUMNS_AUTO_WIFI, deviceData.isAutoWiFi() ? 1 : 0);
        values.put(COLUMNS_MQTT_SERVER, deviceData.getMqttServer());
        values.put(COLUMNS_MQTT_PORT, deviceData.getMqttPort());
        values.put(COLUMNS_MQTT_NAME, deviceData.getMqttName());
        values.put(COLUMNS_MQTT_PSW, deviceData.getMqttPsw());
        values.put(COLUMNS_MQTT_SUB, deviceData.getMqttSub());
        values.put(COLUMNS_MQTT_PUB, deviceData.getMqttPub());
        return databaseUtil.insert(DATA_TABLE, values) > 0;
    }

    /**
     * 更新数据
     *
     * @param deviceData
     * @return
     */
    public boolean update(DeviceData deviceData) {
        ContentValues values = new ContentValues();
        values.put(COLUMNS_DEVICE_ID, deviceData.getDeviceId());
        values.put(COLUMNS_WIFI_NAME, deviceData.getWifiName());
        values.put(COLUMNS_WIFI_PSW, deviceData.getWifiPsw());
        values.put(COLUMNS_AUTO_WIFI, deviceData.isAutoWiFi() ? 1 : 0);
        values.put(COLUMNS_MQTT_SERVER, deviceData.getMqttServer());
        values.put(COLUMNS_MQTT_PORT, deviceData.getMqttPort());
        values.put(COLUMNS_MQTT_NAME, deviceData.getMqttName());
        values.put(COLUMNS_MQTT_PSW, deviceData.getMqttPsw());
        values.put(COLUMNS_MQTT_SUB, deviceData.getMqttSub());
        values.put(COLUMNS_MQTT_PUB, deviceData.getMqttPub());
        return databaseUtil.update(DATA_TABLE, values, SELECT_BY_ID, new String[]{String.valueOf(deviceData.getId())}) > 0;
    }


    /**
     * 删除数据
     *
     * @param deviceData
     * @return
     */
    public boolean delete(DeviceData deviceData) {
        return databaseUtil.delete(DATA_TABLE, SELECT_BY_ID, new String[]{String.valueOf(deviceData.getId())}) > 0;
    }

    /**
     * 根据设备ID获取数据
     *
     * @param deviceId
     * @return
     */
    public DeviceData selectByDeviceId(String deviceId) {
        Cursor cursor = databaseUtil.query(DATA_TABLE,
                new String[]{COLUMNS_ID,
                        COLUMNS_DEVICE_ID,
                        COLUMNS_WIFI_NAME,
                        COLUMNS_WIFI_PSW,
                        COLUMNS_AUTO_WIFI,
                        COLUMNS_MQTT_SERVER,
                        COLUMNS_MQTT_PORT,
                        COLUMNS_MQTT_NAME,
                        COLUMNS_MQTT_PSW,
                        COLUMNS_MQTT_SUB,
                        COLUMNS_MQTT_PUB},
                SELECT_DEVICE_ID,
                new String[]{deviceId}, null, null, null);
        DeviceData deviceData = new DeviceData();
        if (cursor != null && cursor.moveToFirst()) {
            int idIndex = cursor.getColumnIndex(COLUMNS_ID);
            if (idIndex >= 0) {
                deviceData.setId(cursor.getInt(idIndex));
            }
            int deviceIdIndex = cursor.getColumnIndex(COLUMNS_DEVICE_ID);
            if (deviceIdIndex >= 0) {
                deviceData.setDeviceId(cursor.getString(deviceIdIndex));
            }
            int wifiNameIndex = cursor.getColumnIndex(COLUMNS_WIFI_NAME);
            if (wifiNameIndex >= 0) {
                deviceData.setWifiName(cursor.getString(wifiNameIndex));
            }
            int wifiPswIndex = cursor.getColumnIndex(COLUMNS_WIFI_PSW);
            if (wifiPswIndex >= 0) {
                deviceData.setWifiPsw(cursor.getString(wifiPswIndex));
            }
            int autoWifiIndex = cursor.getColumnIndex(COLUMNS_AUTO_WIFI);
            if (autoWifiIndex >= 0) {
                deviceData.setAutoWiFi(cursor.getInt(autoWifiIndex) > 0);
            }
            int mqttServerIndex = cursor.getColumnIndex(COLUMNS_MQTT_SERVER);
            if (mqttServerIndex >= 0) {
                deviceData.setMqttServer(cursor.getString(mqttServerIndex));
            }
            int mqttPortIndex = cursor.getColumnIndex(COLUMNS_MQTT_PORT);
            if (mqttPortIndex >= 0) {
                deviceData.setMqttPort(cursor.getInt(mqttPortIndex));
            }
            int mqttNameIndex = cursor.getColumnIndex(COLUMNS_MQTT_NAME);
            if (mqttNameIndex >= 0) {
                deviceData.setMqttName(cursor.getString(mqttNameIndex));
            }
            int mqttPswIndex = cursor.getColumnIndex(COLUMNS_MQTT_PSW);
            if (mqttPswIndex >= 0) {
                deviceData.setMqttPsw(cursor.getString(mqttPswIndex));
            }
            int mqttSubIndex = cursor.getColumnIndex(COLUMNS_MQTT_SUB);
            if (mqttSubIndex >= 0) {
                deviceData.setMqttSub(cursor.getString(mqttSubIndex));
            }
            int mqttPubIndex = cursor.getColumnIndex(COLUMNS_MQTT_PUB);
            if (mqttPubIndex >= 0) {
                deviceData.setMqttPub(cursor.getString(mqttPubIndex));
            }
        }
        return deviceData;
    }


    /**
     * 数据是否存在
     *
     * @param deviceId
     * @return
     */
    public boolean isExist(String deviceId) {
        Cursor cursor = null;
        try {
            String[] columns = new String[]{COLUMNS_DEVICE_ID};
            String[] selectionArgs = new String[]{deviceId};
            cursor = databaseUtil.query(DATA_TABLE, columns, SELECT_DEVICE_ID, selectionArgs, null, null, null);
            return cursor.getCount() > 0;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return false;
    }

    /**
     * 获取数据列表
     *
     * @param columnNames
     * @param columnValues
     * @param pageNum
     * @return
     */
    public List<DeviceData> getList(String[] columnNames, String[] columnValues, int pageNum) {
        List<DeviceData> dataList = new ArrayList<>();
        Cursor cursor = null;
        try {
            // 计算起始记录的偏移量
            int offset = (pageNum - 1) * LIMIT;
            // 拼接查询参数
            StringBuilder selectionBuilder = new StringBuilder();
            if (columnNames == null || columnValues == null || columnNames.length == 0 || columnValues.length == 0) {
                cursor = databaseUtil.query(DATA_TABLE, null, null, null, null, null, null, offset + "," + LIMIT);

            } else {
                for (int i = 0; i < columnNames.length; i++) {
                    selectionBuilder.append(columnNames[i]).append("=?");
                    if (i != columnNames.length - 1) {
                        selectionBuilder.append(" AND ");
                    }
                }
                String selection = selectionBuilder.toString();
                cursor = databaseUtil.query(DATA_TABLE, null, selection, columnValues, null, null, null, offset + "," + LIMIT);
            }
            while (cursor.moveToNext()) {
                DeviceData deviceData = new DeviceData();
                int idIndex = cursor.getColumnIndex(COLUMNS_DEVICE_ID);
                if (idIndex >= 0) {
                    deviceData.setId(cursor.getInt(idIndex));
                }
                int deviceIdIndex = cursor.getColumnIndex(COLUMNS_DEVICE_ID);
                if (deviceIdIndex >= 0) {
                    deviceData.setDeviceId(cursor.getString(deviceIdIndex));
                }
                int wifiNameIndex = cursor.getColumnIndex(COLUMNS_WIFI_NAME);
                if (wifiNameIndex >= 0) {
                    deviceData.setWifiName(cursor.getString(wifiNameIndex));
                }
                int wifiPswIndex = cursor.getColumnIndex(COLUMNS_WIFI_PSW);
                if (wifiPswIndex >= 0) {
                    deviceData.setWifiPsw(cursor.getString(wifiPswIndex));
                }
                int autoWifiIndex = cursor.getColumnIndex(COLUMNS_AUTO_WIFI);
                if (autoWifiIndex >= 0) {
                    deviceData.setAutoWiFi(cursor.getInt(autoWifiIndex) > 0);
                }
                int mqttServerIndex = cursor.getColumnIndex(COLUMNS_MQTT_SERVER);
                if (mqttServerIndex >= 0) {
                    deviceData.setMqttServer(cursor.getString(mqttServerIndex));
                }
                int mqttPortIndex = cursor.getColumnIndex(COLUMNS_MQTT_PORT);
                if (mqttPortIndex >= 0) {
                    deviceData.setMqttPort(cursor.getInt(mqttPortIndex));
                }
                int mqttNameIndex = cursor.getColumnIndex(COLUMNS_MQTT_NAME);
                if (mqttNameIndex >= 0) {
                    deviceData.setMqttName(cursor.getString(mqttNameIndex));
                }
                int mqttPswIndex = cursor.getColumnIndex(COLUMNS_MQTT_PSW);
                if (mqttPswIndex >= 0) {
                    deviceData.setMqttPsw(cursor.getString(mqttPswIndex));
                }
                int mqttSubIndex = cursor.getColumnIndex(COLUMNS_MQTT_SUB);
                if (mqttSubIndex >= 0) {
                    deviceData.setMqttSub(cursor.getString(mqttSubIndex));
                }
                int mqttPubIndex = cursor.getColumnIndex(COLUMNS_MQTT_PUB);
                if (mqttPubIndex >= 0) {
                    deviceData.setMqttPub(cursor.getString(mqttPubIndex));
                }
                dataList.add(deviceData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return dataList;
    }


    /**
     * 获取总记录数
     *
     * @param columnValues
     * @return
     */
    public int getTotalRecordCount(String[] columnValues) {
        int count = 0;
        Cursor cursor = null;
        try {
            if (columnValues == null) {
                cursor = databaseUtil.rawQuery("SELECT COUNT(*) FROM " + DATA_TABLE, null);
            } else {
                cursor = databaseUtil.rawQuery("SELECT COUNT(*) FROM " + DATA_TABLE + " WHERE device_id = ?", columnValues);
            }

            if (cursor.moveToFirst()) {
                count = cursor.getInt(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return count;
    }
}
